﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.Web.Routing;

namespace Mindfor.Web
{
	/// <summary>
	/// Represents controller factory that can create controllers in modules.
	/// </summary>
	public class CmsControllerFactory : DefaultControllerFactory
	{
		protected override Type GetControllerType(RequestContext requestContext, string controllerName)
		{
			// get module name from request route data
			object obj;
			if (requestContext.RouteData.Values.TryGetValue("module", out obj))
			{
				string moduleName = obj as string;
				if (!String.IsNullOrEmpty(moduleName))
				{
					// find module
					ModuleBase module = ModuleFactory.Default.Modules[moduleName];
					if (module == null)
						throw new ModuleException(moduleName, String.Format("Module \"{0}\" specified in route does not exists or nor enabled.", moduleName));

					// find controller
					ControllerDescriptor controller = module.GetController(controllerName);
					if (controller == null)
						return null;
					return controller.ControllerType;
				}
			}
			
			// call base if module-controller not found
			return base.GetControllerType(requestContext, controllerName);
		}
	}
}
